Skip to content

feat: CC Switch-aligned parameters, stream idle watchdog, and release-line reset - #597

Closed
guyu233 wants to merge 64 commits into
caigee-cmd:mainfrom
guyu233:main
Closed

guyu233 wants to merge 64 commits into
caigee-cmd:mainfrom
guyu233:main

Conversation

@guyu233

@guyu233 guyu233 commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

What this changes

Everything the fork accumulated since 5861ffe, consolidated into one PR: CC Switch-aligned parameter handling, console/runtime hardening, a stream idle watchdog, and the fork's release-line reset.

Parameter handling

  • Reasoning effort (internal/providers/reasoning.go, workbuddy/mapping.go): a level the client sends is forwarded untouched whenever the model declares it; an undeclared level degrades to the nearest lower declared tier; a request below the floor lands on the cheapest declared tier; an omitted level is the only case that uses the model default. A reasoning mismatch never moves the request to another provider, and none on a model that cannot disable thinking no longer falls back to a possibly higher default.
  • Output and context limits (internal/executor, internal/gateway, internal/translate): max_tokens / max_output_tokens are forwarded exactly as sent. No implicit default is injected, so a request that omits the field keeps the upstream's own decision. The models the gateway serves advertise context_length / max_output_tokens in /v1/models, and the client sizes its own request from that.
  • Console capability editing (internal/accounts, frontend): the arbitrary 1024 floor and the "max output ≤ context" cross-field rule are gone; both values are validated only as non-negative integers with a sane upper bound, matching the optional, unconstrained columns CC Switch exposes.

Runtime and reliability

  • Stream idle deadline (internal/executor/stream_idle.go): a stream that returns 200, emits its first event, then goes silent is now bounded by a five-minute idle deadline (CLI2API_STREAM_IDLE_MS, clamped to 30s minimum). The timer only runs while a read is actually waiting on the upstream body, so a blocked client write cannot kill a healthy stream. On expiry the inner body is closed, the in-flight slot is released, and the failure is classified as stream_idle_timeout (unavailable, 10s cooldown, no failover, transient).
  • Abandoned request rows (internal/store, internal/app): process startup closes request logs left in started / streaming by the previous process as error / stream_abandoned, so the console no longer shows multi-hour ghost streams.
  • Cross-provider aggregation still does not fan out: one request acquires exactly one in-flight slot.

Console and runtime

  • Real checkbox reasoning-tier picker for logical models (HeroUI, per-tier Chinese meaning, select-all/clear, legal default enforcement).
  • Capability overrides on aggregation models, isolated from the shared server catalog.
  • Bulk account re-login walkthrough; runtime state pushed over SSE; bulk operations run fully concurrent.
  • Gateway: damaged tool-call arguments are repaired and normalized instead of failing the round, and same-tool calls that reuse index 0 stay separate.
  • Check-in schedule follows the per-provider setting and learns the daily window per region.

Release tooling

  • release.yml accepts an explicit x.y.z only when it is exactly the next patch after the latest published release; line changes go through bump=minor / bump=major, and allow_rewind is only for a deliberate reset with the old tag deleted first.
  • Update checks follow the GitHub latest marker instead of the highest semver tag, so a deliberately reset numbering line still reports the newest build.
  • Updater pull retries are bounded, the host updater binary comes from the pulled image, and health verification accepts the tag-prefixed version as well as the bare one (0.7.52 vs v0.7.52).

Fork release-line reset

  • Withdrew the fork builds v0.7.46–v0.7.61 (16 releases and tags; release notes backed up locally), keeping v0.7.44 (upstream) and v0.7.45.
  • Reissued 0.7.46 from current main (d68bf36): image ghcr.io/guyu233/cli2api:0.7.46, marked Latest; the live host runs v0.7.46. Withdrawn CHANGELOG.md sections were removed so the archive job can write the new notes under the same number.
  • Next releases continue 0.7.47, 0.7.48, … with no gaps.

Verification

  • go test ./... passes (api, app, console, control, executor, gateway, logs, runtime, store, update, updater and every provider package).
  • go build ./... passes; gofmt reports no changes in the files touched by this PR.
  • v0.7.46 release run: prepare, assets, draft, image, promote, publish, aliases and changelog — all eight jobs succeeded.
  • Live host after cutover: /health returns version: v0.7.46, commit: d68bf36; container Up (healthy); console / returns 200; no panic / fatal / level=error lines since the switch; /api/system/update reports current_version: v0.7.46, has_update: false, rollback only v0.7.45.
  • python scripts/release-notes.py validate exits 0; bilingual fragments live under changelog/unreleased/.

Notes

  • stream_idle_timeout is covered by internal/executor/stream_idle_test.go (silent stream fires, active stream survives, blocked consumer is not killed, slot released on close, classification) and internal/store/request_logs_abandoned_test.go.
  • Console changes were followed by cd frontend && npm run sync, so internal/webui/static matches frontend/dist.

guyu233 and others added 30 commits November 24, 2026 16:13
Routing stability for cache affinity:

- Retry a transient upstream hiccup once on the same account before spending
  a failover hop. An empty stream, a first-byte timeout, or a stream that dies
  before the first event usually recovers on the same worker, and switching
  accounts throws away the prompt cache. The retry has its own per-request
  budget, keeps the in-flight slot, and skips any non-transient failure.
- Stop the exponential ladder from multiplying a cooldown the upstream declared
  itself. Transient failures are capped at 60s; a quota reset reported in the
  response body is used verbatim (>=1m, <=24h) instead of being clamped to the
  10-minute rate-limit window, which would have retried a dead account every
  ten minutes. Durable failures (auth, unhinted rate limits) still escalate.
- Keep a session binding through a short cooldown: failover no longer clears the
  anchor when the account is only cooling, and bindSession/CommitSession leave
  the anchor alone while its remaining cooldown is 5 minutes or less, so the
  next turn returns to the cache-warm account.
- Default session-affinity TTL 1h -> 4h, with CLI2API_AFFINITY_TTL and
  CLI2API_AFFINITY_CAPACITY overrides (48h / 1M bindings hard caps).
- Classify exhausted routing (503 no_accounts) and undecodable upstream bodies
  (502 upstream_decode_error) instead of leaking a bare 502 upstream_error.

Observability, so the change can be measured:

- SessionAffinityStats gains miss_reasons / escape_reasons distributions
  alongside the existing last-value fields.
- RequestUsageTotals gains cache_hit_rate (hit / (hit + miss)), nil when no
  cache accounting was reported.
- SeedComponents reports per-component session-seed hashes; Prepare logs them
  under CLI2API_AFFINITY_DEBUG so a chat that re-anchors every turn can be
  traced to a volatile system prefix or a changed first message.
Two remaining cache-hit leakers:

- Normalize the tools array before hashing the session seed. Tool definitions
  are a set, but clients such as Claude Code and Cline rebuild the array per
  turn; an order change used to move the seed, scatter the chat across accounts
  and invalidate the upstream cached prefix. NormalizeToolsOrder sorts by tool
  name plus the compact body so identical sets hash identically, returns input
  byte-identical when already sorted, and leaves invalid/empty/unnamed input
  untouched. Payload reordering is opt-in via CLI2API_TOOLS_NORMALIZE because
  some models notice the array order; the fingerprint side is always on.
- Escape a sticky provider binding when the whole provider is cooling for a
  real reason (quota, or a retry hint of two minutes or more) and a different
  provider family can serve the model. Previously only concurrency saturation
  could escape, so a quota-exhausted provider answered 429 while a healthy
  supplier sat idle. capacityOutsideProvider deliberately excludes same-family
  region hops (Qoder global/CN are isolated upstreams), and the escape keeps
  stickyEscape so a successful turn does not steal the anchor while the bound
  account is merely cooling; short cooldowns still return a Retry-After.
Conflict resolution:
- keep upstream's standalone const pathCheckinStatus in checkin.go and drop the
  duplicate declaration from credential.go (upstream caigee-cmd#586 shipped the probe).
- drop the duplicated checkin-status tests from client_test.go; upstream caigee-cmd#586
  already carries them in checkin_status_test.go.

Verified on the merged tree: go build ./..., go test ./..., go vet ./...
- config: read UPDATE_GITHUB_REPO (default caigee-cmd/cli2api) and feed it to
  the release checker instead of a hardcoded repository.
- updater: add -github-repo so a host updater self-updates from the same fork;
  ExecutorConfig already falls back to the upstream default when empty.
- deploy: pass UPDATE_GITHUB_REPO through compose, document it in .env.example,
  and let install-updater.sh / install-updater.ps1 honor
  CLI2API_IMAGE_REPOSITORY and CLI2API_GITHUB_REPOSITORY.
- tests: cover the config default/override and executor repository resolution.
The create dialog rendered its error alert at the top of the scrollable body,
so a validation failure was invisible once the member list was scrolled; the
client also accepted ids the server rejects (dots, underscores, spaces).

- validate the model id in the dialog with the same character set the backend
  enforces and explain the failure in place.
- pin the form error above the footer so it stays on screen.
- return a precise backend message for a malformed id instead of "required".
- cover valid/invalid ids and the message with tests; refresh static assets.
- config: UPDATE_GITHUB_REPO now defaults to guyu233/cli2api and normalizes owner/repo, GitHub URLs and .git suffixes; the console shows the resolved repository.
- updater: -image-repository/-github-repo default to the fork image and releases so a host updater pulls and self-updates from the same place.
- deploy: compose image, .env.example and both installers follow the fork; README documents UPDATE_GITHUB_REPO and the installer overrides.
- console: the update panel names the release source and, when no host updater is connected, explains that deploy/install-updater.sh has to be installed once instead of reporting a generic outage; failed prepares name the missing daemon too.
- sync rebuilt frontend static; full go test/vet and npm lint pass.
…release

A fork that only carries tags used to compute v0.1.0; release.yml now falls back to the highest semantic tag reachable from the release commit, so the first fork release continues the version line.
Keep the changelog fragments and drop the archived 0.7.47 section so the next release publishes as v0.7.45; the following bump becomes v0.7.46.
…ent upstream releases

- trae: X-Ide-Version-Code 20260212 -> 20261117. Trae gates the model catalog and chat on the build date; the old value collapsed the catalog to the legacy six models and rejected current ones with 4001. Adds a cohort guard test. UG check-in/quota live-verified unchanged.

- workbuddy: CLI segment 2.176.0 -> 2.186.0 (CN desktop 5.11.3 / Global 5.11.4 stay). Live A/B: same 57-model CN catalog and streaming chat; billing check-in / user-resource untouched.

- kiro: IDE fallback 1.4.236 -> 1.5.37. codex: UA 0.172.0. command: CLI 1.93.3. kimi: CLI 2.7.3. devin: CLI 3000.14.30821.
The wire version string was 3.4.24, a number that does not appear in trae.cn's public release line (3.4.21 shipped 2026-11-17, and nothing newer is published). Trae does not gate the catalog on this string, but reporting an unpublished build still misdescribes the client, so it now carries the same 3.4.21 release as the 20261117 build code.

Re-audited every other pin against its public source on 2026-11-25: Kiro IDE 1.5.37 (stable metadata), Codex 0.172.0 (published 11-24), Command 1.93.3 (published today), Kimi 2.7.3, Devin 3000.14.30821 (11-17), WorkBuddy CLI 2.186.0 with desktop 5.11.3/5.11.4, QwenWork 2.1.0/26111906. All are the newest published builds and stay unchanged.
…uilds

Meta Muse: chat now sends muse-build/1.4.14 with build dec7d749... (the pair captured from Muse Code 1.4.14-R7309.1 and still shipped by CLIProxyAPI main), tbh:exec and the host platform, replacing the stale 1.3.0 / tbh:tui identity. The 1.4.25 client exists but has no published build hash, and a new version with an old hash is an inconsistent fingerprint.

MiniMax: the check-in query reports desktop_version=0.7.9, the current MCode TUI release (npm @minimax-ai/code, 2026-11-20), instead of 0.7.2. The route signs the exact path+query, so this only changes the attribution field.
Qoder: check-in reports the desktop release per edition (CN 0.5.18, 2026-11-24; global 0.5.3, 2026-11-03) instead of 0.4.8.

CodeArts: login reports snap_vscode / 26.11.300. Both the IDE 26.11.200 package (bundled huaweicloud.codearts-snap) and the 26.11.300 VSIX build plugin-name as \_vscode and send the raw extension version; neither contains snap_AIIDE or 5.2.0.

Kiro: KAS moves to 0.66.123, the @kiro/agent version bundled in IDE 1.5.37 (kiro.kiro-agent 1.1.1168, commit 03cd03a).

Doubao Work: account query reports sdk_version 2.2.10, the value doubao.com requests today; version_code 20800 is kept because the official page still sends it.
- Model pool editor can pin context window, max output, reasoning levels and
  default effort for an aggregated model; /v1/models advertises exactly those
  values.
- Aggregations without overrides advertise the conservative intersection of
  their members (smallest window and output, shared reasoning levels) instead
  of the first member's numbers, and members resolve by provider and region
  rather than by model name alone.
- A request that carries no reasoning intent uses the aggregation default level;
  each member provider still maps and clamps it to what its own model allows.
… concurrent

- Check-in all and refresh credits fan out to every account in one pass: the new
  bulk endpoints return one result per account with the verbatim upstream error,
  and the console no longer batches or queues requests.
- GET /api/events streams the runtime event bus (account / accounts / quota /
  checkin / refresh / bulk) with sequence replay. Console pages patch rows live
  and fall back to a 5s poll when the stream is unavailable.
- Check-in results carry the real reward credits plus code and HTTP status, and a
  provider that reports no status stays "unknown" instead of "success".
- Quota is persisted as the real upstream snapshot; force-ready overrides only
  enter the routing pool and the console badges them. Each quota snapshot states
  its age, and the synthetic inflight demo board plus its login showcase are gone.
- Video, audio and file content parts are refused with a real 400 invalid_request
  instead of being dropped during prompt assembly, and a shared head timeout makes
  Trae streams fail over when the upstream accepts a request and stays silent.
Select account cards, confirm, and the console authorizes them one at a time: start the provider login, show the authorization page, poll status, and advance automatically. Cancel stops the walkthrough; every row keeps its own state and the verbatim upstream message.
The implicit max-output default changed what every client asked for without its knowledge. Similar gateways do not do this: one-api passes the request body through, and LiteLLM only fills a default where the upstream protocol requires max_tokens. Keep the catalog limits in /v1/models and let the client size its own request.
Renumbering a released build needs a version number that sits below the latest tag. Guard it behind allow_rewind so the default still refuses to move backwards, and require the target tag to be deleted first.
0.45.x sorts above 0.7.45 in SemVer, so the console kept offering 0.45.2 as the newest release after the renumbering. Read /releases/latest and let the marked release decide the update target; fall back to the highest tag only when no marker is available.
@caigee-cmd

Copy link
Copy Markdown
Owner

Not merging this as one pull request. The branch is guyu233/cli2api's main (57 commits, 266 files, +8417/−1660) and it rewrites this repository's release identity.

Blocking

The defaults that decide where an installation pulls images and checks for updates are changed from caigee-cmd/cli2api to guyu233/cli2api:

  • deploy/docker-compose.yml image default → ghcr.io/guyu233/cli2api:latest
  • internal/config/config.go DefaultUpdateGitHubRepo → guyu233/cli2api
  • cmd/updater/main.go and internal/updater/executor.go image and GitHub-repo defaults
  • deploy/install-updater.sh and deploy/install-updater.ps1

Merged here, a stock deploy would pull the fork's image and follow the fork's releases. CHANGELOG.md is also rewritten so 0.7.45 is a different release than the one already published on this repository (fork 0.7.46–0.7.49 are archived into the file). Please retarget these at caigee-cmd/cli2api and keep the fork defaults on the fork.

Please split out, these change request behavior

Worth taking, but each one moves routing, billing, or what the client is told, so they need their own review:

  • Session affinity: default TTL 1h → 4h, cooldown failures no longer drop the anchor, and a cooling provider can be escaped when another family has capacity (internal/executor/chat.go, session_affinity.go).
  • Same-account retry of a transient failure before failover spends a hop.
  • Quota cooldown taken verbatim from the upstream reset (up to 24h) instead of the local-midnight fallback (internal/executor/classify.go).
  • Reasoning effort now degrades downward to the cheapest declared tier instead of the model default, including none on a model that cannot disable thinking (internal/providers/reasoning.go, workbuddy/mapping.go).
  • Damaged tool-call arguments are repaired or trimmed to {} instead of failing the turn (internal/translate/toolargs.go). Repairing a truncated argument can call a tool with arguments the model did not finish.
  • Aggregation models gain capability overrides and a new SQLite migration (034_aggregation_capabilities.sql).
  • release.yml allow_rewind can republish a version below the latest tag.

Fine once the above is split out

Provider version pins, per-region check-in windows, bounded docker pull retries, updater binary taken from the pulled image, console SSE for account state, and the bulk re-login walkthrough. CI on this head is green (go, worker, frontend, container, windows-host, secrets).

Happy to review those as separate PRs.

@caigee-cmd

Copy link
Copy Markdown
Owner

补充一下具体可以怎么改。上面提到的功能本身大多是想要的,卡的是「整支 main 一起合」以及发布源被改成了 fork。按下面拆开之后,我可以逐个看完就合。

1. 发布源改回这个仓库

这几处默认值现在指向 guyu233/cli2api。合进来之后,按默认配置部署的实例会去拉 fork 的镜像、跟 fork 的发布。请改回 caigee-cmd/cli2api 和 ghcr.io/caigee-cmd/cli2api:

  • deploy/docker-compose.yml 里 CLI2API_IMAGE 的默认镜像
  • internal/config/config.go 的 DefaultUpdateGitHubRepo
  • cmd/updater/main.go 的 --image-repository、--github-repo 默认值
  • internal/updater/executor.go 里配置为空时的同样两个默认值,以及对应测试里写死的 guyu233/cli2api
  • deploy/install-updater.sh、deploy/install-updater.ps1 的默认仓库
  • deploy/.env.example、deploy/README.md 里对应的说明

UPDATE_GITHUB_REPO、CLI2API_IMAGE_REPOSITORY、CLI2API_GITHUB_REPOSITORY 这些覆盖开关可以留着,只是不设置时的默认值请仍是本仓库。fork 如果要默认跟自己的发布,放在 fork 自己的分支上即可,不必写进这里。

CHANGELOG.md 里归档的 0.7.45–0.7.49 是 fork 上已经发出的版本,和本仓库已发布的 0.7.45 不是同一份内容。请不要改写已经发布的条目;这次的说明继续放在 changelog/unreleased/,等本仓库发版时再归档。

2. 会改变请求行为的部分,请各自开一个 PR

这几块各自改的是路由、配额或客户端拿到的结果,放在一起很难单独回退。建议从现在这个分支上按主题拆出去,每支都基于最新的 caigee-cmd/cli2api main:

  1. 会话亲和(internal/executor/chat.go、session_affinity.go):默认 TTL 从 1 小时改为 4 小时、冷却中的失败不再丢掉锚点、整个供应商冷却时可以逃到另一个供应商家族。
  2. 同一账号先重试一次:瞬时失败(空流、首字节超时)先在原账号重试,再考虑故障转移。
  3. 配额冷却(internal/executor/classify.go):改为直接采用上游给的重置时间,最长 24 小时,不再用本地午夜兜底。
  4. reasoning 向下退化(internal/providers/reasoning.go、internal/providers/workbuddy/mapping.go):模型没声明的档位退到更低的已声明档,而不是退回模型默认值;none 打到不能关思考的模型时,落到最便宜的思考档。
  5. 损坏的 tool call 参数(internal/translate/toolargs.go 以及 gateway 里的流式归一化):修补后继续这一轮,修不好则收成 {}。这条想单独看一下截断参数被补全之后,会不会拿模型没写完的参数去调工具。
  6. 聚合模型的能力覆盖,连同新的 SQLite migration 034_aggregation_capabilities.sql。已发出的 migration 不要改,这条作为新的一条追加是对的。
  7. release.yml 的显式版本和 allow_rewind,以及用 /releases/latest 而不是最高 tag 来决定更新目标。allow_rewind 请保持默认关闭。

3. 这些拆出来就可以直接过

供应商版本号对齐、按区域学习签到窗口、docker pull 限时并重试、updater 二进制改从拉下来的镜像里取、控制台用 SSE 推账号状态、批量重新登录。当前这个 head 上 CI(go、worker、frontend、container、windows-host、secrets)已经是绿的。

操作上不必改这次提交的历史。从现有分支切出上面的小分支,各自开到本仓库 main 即可;每个 PR 里都不要带上第 1 点那些指向 fork 的默认值。有需要我可以按这个清单帮你对一下拆分后的 diff。

caigee-cmd and others added 3 commits November 26, 2026 13:51
The console asked the operator to flip a Max switch per model before Trae would send is_max_mode. Every other provider simply advertises one context size, so derive the tier from the catalog: models with a real Max window now ask upstream for it on every request, /v1/models advertises the larger window, and the console renders a single value. An explicit client is_max_mode=false still falls back to the default window.
@caigee-cmd

Copy link
Copy Markdown
Owner

看过最新的 head(410bfb5,CI 全绿)。发布源那一组默认值还是 guyu233/cli2api / ghcr.io/guyu233/cli2api,所以这支整体还是先不合,上次列的改法仍然适用。

新加的 trae: unlock the max context tier instead of a per-model switch 单独看是可以合的:声明了更大 Max 档的模型由目录本身解锁,适配器每次请求都向上游要大窗口,客户端显式传 is_max_mode=false 时仍回退到默认窗口,控制台的按模型开关只留给 Qoder。建议和上面第 3 点那些一起,从这支里拆成独立的小 PR。

@guyu233 guyu233 changed the title feat: align parameter handling with CC Switch + console and runtime hardening feat: CC Switch-aligned parameters, stream idle watchdog, and release-line reset Nov 26, 2026
@guyu233

guyu233 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor Author

Splitting this branch per the review. The fork no longer changes the default release identity (defaults stay caigee-cmd/cli2api / ghcr.io/caigee-cmd/cli2api; a fork overrides via UPDATE_GITHUB_REPO / CLI2API_IMAGE_REPOSITORY / CLI2API_GITHUB_REPOSITORY). This PR is replaced by the core PR plus #598 (tool-call arguments), #599 (reasoning levels), #600 (executor affinity/retry/quota); aggregation caps, console SSE and bulk re-login follow separately.

@guyu233 guyu233 closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants